package com.lbkj.wsc;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XmlUtils {
    private static final Logger log = LoggerFactory.getLogger(XmlUtils.class);
    private static final XmlMapper xmlMapper = new XmlMapper();


    static {
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        // de
        xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static String beanToXml(Object bean) {
        String xml = "";
        try {
            xml = xmlMapper.writeValueAsString(bean);
        } catch (JsonProcessingException e) {
            log.error("jackson bean to xml error", e);
        }
        return xml;
    }

    public static String beanToXmlWithHeader(Object bean) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + beanToXml(bean);
    }

    public static <T>  T xmlToBean(String xml, Class<T> clazz) {
        try {
            return xmlMapper.readValue(xml, clazz);
        } catch (JsonProcessingException e) {
            log.error("jackson xml to bean error", e);
        }
        return null;
    }
}
